#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
IncludePath="/opt/coopip/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject.settings
setup_environ(djangoproject.settings)
from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
import CIS, AMR, OMS, GIS
from django.contrib.gis.db import models
#********************Setup psycopg2 and django section********************
from django.db import transaction

import urllib
import httplib
import datetime
import ftplib
import telnetlib
import COOPIP_Misc

LocalFilePath='/opt/coopip/outgoingftp/'

LocalFileName='LocationInfoUpdate.txt'
RemoteFileName='workfile/locinf'
FTPLoginUsername='casystem'
FTPLoginPassword='Siren20!'
FTPServer='192.168.100.1'
TelnetLoginUsername=FTPLoginUsername
TelnetLoginPassword=FTPLoginPassword
TelnetServer=FTPServer



def GetCISIdentifierForBoardDistrictPolygon(station):
    PotentialDistrict = GIS.Coopgisboarddistrict.objects.filter(the_geom__contains=station.the_geom)
    if(PotentialDistrict and PotentialDistrict[0].cisidentifier):
        return PotentialDistrict[0].cisidentifier
    else:
        return ''


def GetCISIdentifierForCountyPolygon(station):
    PotentialCounty = GIS.Coopgiscounty.objects.filter(the_geom__contains=station.the_geom)
    if(PotentialCounty and PotentialCounty[0].cisidentifier):
        return PotentialCounty[0].cisidentifier
    else:
        return ''



def CalculateBatchRow(MeterOrLight, LightIndicator=False):
    Results = []
    #Any blank items are ignored by the batch interface
    if(LightIndicator):
        Results.append(str(MeterOrLight.mapnumber) + ',') #LOCATION
    else:
        Results.append(COOPIP_Misc.GetLongMapNumber(MeterOrLight) + ',') #LOCATION
        if('invalid' in str(Results).lower()):
            return 'UNKNOWN'
    Results.append(',') #DIST
    Results.append(GetCISIdentifierForCountyPolygon(MeterOrLight.station) + ',') #COUNTY
    Results.append(',') #CITY
    Results.append(',') #TAXDIST
    Results.append(GetCISIdentifierForBoardDistrictPolygon(MeterOrLight.station) + ',') #BOARD
    Results.append(',') #TAXCD
    Results.append(',') #SUBS
    Results.append(',') #CIR
    Results.append(',') #LSEC
    Results.append(',') #PH
    Results.append(',') #BKR
    Results.append(',') #ID
    #Results.append(',') #Test
    if(LightIndicator):
        Results.append(str(MeterOrLight.mapnumber) + ',') #NEW Location Number
    else:
        Results.append(COOPIP_Misc.GetLongMapNumber(MeterOrLight) + ',') #NEW Location Number
    TempPoint=MeterOrLight.station.the_geom.transform(4326, clone=True) 
    Results.append(str(TempPoint.y)[:10] + ',') #LATITUDE
    Results.append(str(TempPoint.x)[:10]) #LONGITUDE
    return ''.join(Results)

def CreateLocalLocationInfoUpdateFile():
    Rows = []
    Meters=GIS.Coopgisassembly.objects.all().filter(compatibleunit__meterindicator=True)
    for meter in Meters:
        BatchRow=CalculateBatchRow(meter) + '\n'
        if('UNKNOWN' in BatchRow):
            continue
        Rows.append(BatchRow)
    print Rows[0]
    print Rows[1]
    print Rows[2]

    Lights=GIS.Coopgisassembly.objects.all().filter(compatibleunit__lightindicator=True)
    for light in Lights:
        BatchRow=CalculateBatchRow(light, LightIndicator=True) + '\n'
        if('UNKNOWN' in BatchRow):
            continue
        Rows.append(BatchRow)
 

    OutputFile=open(LocalFilePath + LocalFileName, 'w')
    OutputFile.writelines(Rows)
    OutputFile.close()

def Upload(ftp):
    ext = os.path.splitext(LocalFileName)[1]    
    if ext in (".txt", ".htm", ".html"):
        LocalFile=open(LocalFilePath + LocalFileName, 'r')
        ftp.storlines("STOR " + RemoteFileName, LocalFile)
    else:
        LocalFile=open(LocalFilePath + LocalFileName, 'rb')
        ftp.storbinary("STOR " + RemoteFileName, LocalFile, 1024)
    LocalFile.close()



CreateLocalLocationInfoUpdateFile()

ftp = ftplib.FTP(FTPServer)
ftp.login(FTPLoginUsername , FTPLoginPassword)
Upload(ftp)

telnet=telnetlib.Telnet(TelnetServer)
telnet.set_debuglevel(2)

telnet.read_until("login: ")
telnet.write(TelnetLoginUsername + "\n")
telnet.read_until("Password: ")
telnet.write(TelnetLoginPassword + "\n")
telnet.read_until("$")
telnet.write("run pub/genlocup\n")
telnet.read_until("Y/N")
telnet.write("N\n")
telnet.read_until("Y/N/S/E")
telnet.write("Y\n")
telnet.read_until("$")
telnet.write("exit\n")
print telnet.read_all()

                 
    
